from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login, logout
from .models import *
from django.db.models import F
import datetime
import random


#   注册 /account/register/
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        objects = User.objects.create_user(username=username, password=password)
        UserMoney.objects.create(user_id=objects)
        return render(request, 'account/login.html')
    return render(request, 'account/register.html')


#   登录 /account/login/
def logins(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        result = authenticate(username=username, password=password)
        if result:
            login(request, result)
            content = dict()
            content['balance'] = UserMoney.objects.filter(user_id=result)
            return render(request, 'account/list.html', content)
    return render(request, 'account/login.html')


#   返回总列表
def list(request):
    content = dict()
    content['balance'] = UserMoney.objects.filter(user_id=request.user)
    return render(request, 'account/list.html', content)



#   注销 /account/logouts/
def logouts(request):
    logout(request)
    return render(request, 'account/login.html')


#   修改密码 /account/change_password/
def change_password(request):
    if request.method == "POST":
        password = request.POST.get('password', '')  # 获取密码，默认为空字符串
        confirm = request.POST.get('confirm_password', '')  # 获取确认密码，默认为空字符串

        if password == '' or confirm == '': # 如果密码或确认密码为空
            msg = '用户名或密码不能为空'
        elif password != confirm:  # 如果密码与确认密码不一致
            msg = '两次输入的密码不一致'
        else:
            user = User.objects.get(username=request.user)  # 获取用户对象
            print(user)
            user.set_password(request.POST.get('password'))  # 设置对象的密码
            user.save()
            return render(request, 'account/login.html')
    return render(request, 'account/change_password.html')


#   充值页面 /account/recharge/
def recharge(request):
    if request.method == "POST":
        UserMoney.objects.filter(user_id=request.user).update(balance=F('balance')+int(request.POST.get('number')))
        content = dict()
        content['balance'] = UserMoney.objects.filter(user_id=request.user)
        RangeRMB.objects.create(user_id=request.user, change_morey=int(request.POST.get('number')),
                                change_type=0,change_time=datetime.datetime.now(), order_no=random.randint(10000, 99999))
        # UserOrder.objects.create(order_no=random.randint(10000, 99999), user_id=request.user, commodity_no=)

        return render(request, 'account/list.html', content)
    return render(request, 'account/recharge.html')


#   充值记录 /account/recharge/history/
def recharge_history(request):
    content = dict()
    users = request.user
    print(users)
    content['all'] = users.rangermb_set.all()
    return render(request, 'account/recharge_history.html', content)

#   订单记录 /account/order/self/
def order_self(request):
    content = dict()
    content['all'] = request.user.userorder_set.all()
    return render(request, 'account/order_self.html', content)



#   商品总列表
def commodity(request):
    content = dict()
    content['all'] = Commodity.objects.all()
    content['option'] = CommodityCategory.objects.all()
    return render(request, 'commodity/commodity.html', content)


#   指定类别商品列表
def category_id(request):
    content = dict()
    if request.method == "GET":
        data = request.GET.get("CommodityCategory")
        object = CommodityCategory.objects.get(pk=data)
        content['all'] = object.commodity_set.all()
        content['option'] = CommodityCategory.objects.get(pk=data)
    return render(request, 'commodity/category_id.html', content)


#   指定商品详情页面
def commodity_no(request, commodity_no):
    object = Commodity.objects.get(commodity_no=commodity_no)
    return render(request, 'commodity/commodity_no.html', {'object': object})


#   下订单
def add_order(request):
    id = request.POST['commodity_no']
    pay = Commodity.objects.get(commodity_no=id).price
    objects = UserOrder.objects.filter(commodity_no=id).exists()
    if objects == True:
        UserOrder.objects.filter(commodity_no=id).update(buy_count=F('buy_count') + 1,
                                                         pay_money=F('pay_money')+pay)
    else:
        UserOrder.objects.create(order_no=str(random.randint(10000, 99999)), user_id=request.user,
                                 commodity_no=id, pay_money=pay, pay_time=datetime.datetime.now(),
                                 add_time=datetime.datetime.now())
    Commodity.objects.filter(commodity_no=id).update(stock=F('stock') - 1)

    return HttpResponse('1')


#   中奖
def is_good(request, commodity_no):

    pass
    # content = dict()
    # content['all'] = Commodity.objects.all()
    # content['option'] = CommodityCategory.objects.all()
    return HttpResponse('ok')